<template>
  <Sidebar ref="sidebarRef" :title="t('note.title')">
    <div class="noteContentWrap" ref="noteContentWrapRef"></div>
  </Sidebar>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount, defineProps } from 'vue'
import Sidebar from './Sidebar.vue'
import { useMainStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'
import { useEventBus } from '@/hooks'
import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer'
import '@toast-ui/editor/dist/toastui-editor-viewer.css'

const props = defineProps({
  mindMap: {
    type: Object
  }
})

const store = useMainStore()
const { isDark, activeSidebar } = storeToRefs(store)
const { setActiveSidebar } = store
const { t } = useI18n()
const { $on, $off, $emit, $once } = useEventBus()

const sidebarRef = ref(null)
const noteContentWrapRef = ref(null)
const editor = ref(null)
const node = ref(null)

watch(activeSidebar, (val) => {
  if (val === 'noteSidebar') {
    sidebarRef.value.show = true
  } else {
    sidebarRef.value.show = false
  }
})

const onNodeActive = (...args) => {
  if (activeSidebar.value !== 'noteSidebar') {
    return
  }
  const nodes = [...args[1]]
  if (nodes.length > 0) {
    if (nodes[0] !== node.value) {
      setActiveSidebar(null)
    }
  } else {
    setActiveSidebar(null)
  }
}

// 初始化编辑器
const initEditor = () => {
  if (!editor.value) {
    editor.value = new Viewer({
      el: noteContentWrapRef.value
    })
  }
}

const onNodeNoteClick = (nodeData) => {
  node.value = nodeData
  setActiveSidebar('noteSidebar')
  editor.value.setMarkdown(nodeData.getData('note'))
}

onMounted(() => {
  $on('node_active', onNodeActive)
  props.mindMap.on('node_note_click', onNodeNoteClick)
  initEditor()
})

onBeforeUnmount(() => {
  $off('node_active', onNodeActive)
  props.mindMap.off('node_note_click', onNodeNoteClick)
})
</script>

<style lang="less" scoped>
.noteContentWrap {
  padding: 12px 20px;
}
</style>
